#!/usr/bin/env python
#encoding=utf-8
import urllib, urllib2
import os
import StringIO
import gzip
import xml.dom.minidom
import xiami_error
import mp3_id3v1_helper

# for debug
debug = 0
def dp(msg):
    if debug:
        print msg

def error(no, msg, abort=True):
    xiami_error.error_no = no
    xiami_error.error_msg = msg
    xiami_error.error_abort = abort

# used for xiami mp3 location decode
def decode_location(location):
    v2 = int(location[0])
    v3 = location[1:]
    v4 = len(v3) / v2
    v5 = len(v3) % v2
    v6 = []

    dp(location)
    dp(v2)
    dp(v3)
    dp(v4)
    dp(v5)

    v7 = 0
    while v7 < v5:
        v6.append(v3[(v4+1)*v7:(v4+1)*(v7+1)])
        v7 += 1
    dp(v6)
    v7 = v5
    while v7 < v2:
        v6.append(v3[(v7-v5)*v4+(v4+1)*v5:(v7-v5+1)*v4+(v4+1)*v5])
        v7 += 1
    dp(v6)

    dp(len(v6[0]))
    v8 = ""
    v7 = 0
    while v7 < len(v6[0]):
        v10 = 0
        while v10 < len(v6):
            if v7 < len(v6[v10]):
                v8 += v6[v10][v7]
                dp(v8)
            v10 += 1
        v7 += 1

    v8 = urllib.unquote(v8)
    dp(v8)

    v9 = ""
    v7 = 0
    while v7 < len(v8):
        if v8[v7] == '^':
            v9 += "0"
        else:
            v9 += v8[v7]
        v7 += 1
    #v9 = v9.replace("+", " ")
    dp(v9)
    return v9

def download(mp3_url, save_path):
    # invalid save_path
    if os.path.exists(save_path):
        error(11, 'failed to download, save_path ['+save_path+'] exists.', abort=False)
        return
    urllib.urlretrieve(mp3_url, save_path)
    # file size check
    if os.path.getsize(save_path) < xiami_error.MIN_FILE_SIZE:
        error(12, 'failed to download, file is too small.', abort=False)
        return

def format_tag(save_path, track_info):
    pass

def format_tag_id3v1(save_path, track_info):
    if os.path.getsize(save_path) < xiami_error.MIN_FILE_SIZE:
        error(12, 'failed to format tag, file is too small.', abort=False)
        return
    mp3_id3v1_helper.update_mp3_tag_id3v1(save_path, track_info)
    
def parse_playlist(playlist_url):
    playlist = []
    opener = urllib2.build_opener()
    opener.addheaders = [
        ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36'),
        ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
        ('Accept-Encoding', 'gzip,deflate,sdch'),
        ('Accept-Language', 'en-US,en;q=0.8,zh-CN;q=0.6'),
        ('Connnection', 'keep-alive'),
        ('Cache-Control', 'max-age=0'),
        ('Host', 'www.xiami.com'),
        ]
    resp = opener.open(playlist_url)
    xml_doc = ''
    if resp.info().get('Content-Encoding') == 'gzip':
        buf = StringIO.StringIO(resp.read())
        f = gzip.GzipFile(fileobj=buf)
        xml_doc = f.read()
    else:
        xml_doc = resp.read()
    if len(xml_doc) < 10:
        error(21, 'failed to get playlist, len(xml_doc) < 10')
        return playlist
    dom = xml.dom.minidom.parseString(xml_doc)
    # capture tracks
    tracks = dom.getElementsByTagName("track")
    attrs = ['song_id', 'title', 'album_name', 'artist', 'location', 'lyric']
    for track in tracks:
        t = {}
        for attr in attrs:
            t[attr] = track.getElementsByTagName(attr)[0].firstChild.wholeText.strip(' ')
        # decode location
        t['location'] = decode_location(t['location'])
        playlist.append(t)
    return playlist

# convert player url to playlist request url
# player_url:
#   http://www.xiami.com/song/play?ids=/song/playlist/id/22925049/type/3
#   http://www.xiami.com/song/play?ids=/song/playlist/id/1771959066%2C1771959067%2C1771959068/object_name/default/object_id/0
# playlist_url:
#   http://www.xiami.com/song/playlist/id/22925049/type/3
#   http://www.xiami.com/song/playlist/id/1771959066,1771959067,1771959068/object_name/default/object_id/0
def get_playlist_url(player_url):
    playlist_url_prefix = 'http://www.xiami.com'
    url = urllib.unquote(player_url)
    play_ids = url.split('?')[1].split('&')[0].split('=')[1]
    return playlist_url_prefix + play_ids

def compose_playlist_url(id_list=[]):
    playlist_url_prefix = 'http://www.xiami.com/song/playlist/id/'
    play_ids = ','.join(id_list)
    return playlist_url_prefix + play_ids

